<template>
  <continer>
    <template slot="content">
      <el-form
        class="m7-form"
        :label-position="labelPosition"
        :rules="rules"
        :model="formData"
        size="mini"
        ref="nodeForm"
      >
        <el-form-item label="节点名称" prop="name">
          <el-input v-model="formData.name" size="mini" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item  prop="url" :rules="[
            { required: true, message: '请求地址必填', trigger: 'change' }
          ]">
          <span slot="label">
                请求地址
               <el-tooltip class="item" effect="dark" content="为提高安全性，建议使用https：开头的地址对接" placement="top">
                  <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
               </el-tooltip>
          </span>
          <el-input v-model="formData.url" size="mini"></el-input>
        </el-form-item>
         <el-form-item label="请求方式" prop="method"  :rules="[
            { required: true, message: '请求方式必选', trigger: 'change' }
          ]">
           <el-radio v-model="formData.method" label='0'>get</el-radio>
           <el-radio v-model="formData.method" label='1'>post</el-radio>
        </el-form-item>
        <el-form-item label="传参方式" prop="method" v-if="formData.method == 1" :rules="[
            { required: true, message: '传参方式必选', trigger: 'change' }
          ]">
          <el-select v-model="formData.contentType" placeholder="请选择传参方式" filterable clearable>
            <el-option v-for="item in methodlist" :label="item.label" :value="item.value" :key="item.label"></el-option>
          </el-select>
        </el-form-item>
        <div v-for="(item, index) in formData.variableList" :key="index">
              <div class="select-group-start" >
                <el-form-item label="参数">
                  <el-cascader
                    style="width: 100%"
                    v-model="item.key"
                    filterable
                    @change="handleChange"
                    :options="cascaderList"
                    :props="{ label: 'memo', value: 'key', emitPath:false }">
                  </el-cascader>
                </el-form-item>
                <el-form-item label="自定义名称" :rules="checkKey" :prop="'variableList.'+index+'.value'">
                  <el-input @blur="checkPublic(item.value)" v-model="item.value"  size="mini"></el-input>
                </el-form-item>
                <div class="select-oprate">
                  <span @click="deleteVariableList(item, index)"><i class="V7_iconfont V7_iconV7tubiao-109 delete-span"></i></span>
                </div>
              </div>
        </div>
        <div class="addVariableList">
             <span @click="addVariableList"><i class="V7_iconfont V7_iconV7tubiao_xinzeng add-span"></i>添加参数</span>
        </div>
        <el-form-item label="请求超时" prop="requestTimeOut" :rules="{required:true,  message: '请输入正整数, 最大值为60', pattern:/(^([1-5])?[0-9]$)|^60$/}">
          <el-input v-model="formData.requestTimeOut" :step="1"  step-strictly>
            <template slot="append">秒</template>
          </el-input>
        </el-form-item>
        <el-form-item label="连接超时" prop="connectTimeOut" :rules="{required:true, message: '请输入正整数, 最大值为60', pattern:/(^([1-5])?[0-9]$)|^60$/}">
          <el-input v-model="formData.connectTimeOut" :step="1"  step-strictly>
            <template slot="append">秒</template>
          </el-input>
        </el-form-item>
        <el-form-item label="返回超时" prop="responseTimeOut" :rules="{required:true, message: '请输入正整数, 最大值为60', pattern:/(^([1-5])?[0-9]$)|^60$/}">
          <el-input v-model="formData.responseTimeOut" :step="1"  step-strictly>
            <template slot="append">秒</template>
          </el-input>
        </el-form-item>
        <p class="instructions"><i class="V7_iconV7tubiao_zhongyaoxiaoxi V7_iconfont"></i>使用须知</p>
        <p class="details">
          1.返回值需要是一层的json结构；<br>
          2.返回的值会存入对应的参数中；<br>
          3.为避免和系统变量混淆,除了code外的接口返回字段增加customer_前缀；<br>
          4.返回值中，code参数需要等于200才会认定交互成功，否则将进入失败转向；<br>
          5.参数数据类型均为字符串格式。
        </p>
        <el-form-item
          :label="item.label"
          prop="region"
          v-for="(item, index) in condition"
          filterable
          :key="index"
        >
          <span slot="label">
            {{item.label}}
            <el-tooltip
              class="item"
              effect="dark"
              :content="index | getTip"
              placement="top"
            >
              <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
            </el-tooltip>
          </span>
          <el-select
            v-model="item.to"
            placeholder="请选择下一步节点"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="(node, index) in nodeList"
              :label="node.data.name"
              :value="node.id"
              v-show="!node.viewOnly && node.id !== currentData.id"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
         <!-- <div class="addCondition">
          <span @click="addCondition"><i class="V7_iconfont V7_iconV7tubiao_xinzeng add-span"></i>添加参数</span>
        </div>
        <el-form-item label="请求超时" prop="name">
          <el-input v-model="num" :step="1"  step-strictly>
            <template slot="append">秒</template>
          </el-input>
        </el-form-item>
        <el-form-item label="链接超时" prop="name">
          <el-input v-model="formData.name" size="mini" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="返回超时" prop="name">
          <el-input v-model="formData.name" size="mini" maxlength="40"></el-input>
        </el-form-item> -->

      </el-form>
    </template>
    <template slot="oprate">
      <el-button @click="cancel" size="mini">取消</el-button>
      <el-button type="primary" @click="onSubmit" size="mini">确定</el-button>
    </template>
    <template slot="remove">
      <el-button @click="deleteNode" type='danger' size="mini">删除</el-button>
    </template>
  </continer>
</template>

<script lang='ts'>

import { Component, Mixins } from 'vue-property-decorator'
import continer from '@/components/configCommon/ui-modules/drawer-container.vue'
import nodeEidtMixins from './nodeEidtMixins'
import { deepClone, commonAction } from '@/utils/common'
@Component({
  name: 'ivr-node-callurl',
  components: { continer },
  filters: {
    getTip (index) {
      if (index === 0) {
        return '数据交互成功，执行此节点。可选当前流程中其他节点+挂断（不选择即为挂断）。'
      } else if (index === 1) {
        return '返回结果code非200的所有情况执行此节点。可选当前流程中其他节点+挂断（不选择即为挂断）。'
      } else if (index === 2) {
        return '请求/连接/返回，任意超时则走此转向。可选当前流程中其他节点+挂断（不选择即为挂断）'
      }
    }
  }
})
export default class extends Mixins(nodeEidtMixins) {
  // private $message
  private methodlist = [
    { label: 'application/x-www-form-urlencoded', value: '1' },
    { label: 'multipart/form-data', value: '2' },
    { label: 'application/json', value: '3' }
  ]

  private minData = {
    key: '',
    value: ''
  }

  private created () {
    this.getPublicCustom()
    if (!this.currentNode.data.hasOwnProperty('variableList')) {
      this.$set(this.currentNode.data, 'variableList', [deepClone(this.minData)])
    }
  }

  private addVariableList () {
    if (this.formData.variableList.length > 100) {
      (this as any).$message.warning('条数不能超过100')
      return
    }
    this.formData.variableList.push(deepClone(this.minData))
  }

  private deleteVariableList (item, i) {
    if (this.formData.variableList.length > 1) {
      this.formData.variableList.splice(i, 1)
    }
  }

  get customParametersList () {
    const arr = deepClone(this.data.nodeList)
    const list = arr.find(item => item.id === 'startNode').data?.customList?.filter(i => i.key) || []
    console.log(list, 121211)
    for (let i = 0; i < list.length; i++) {
      const element = list[i]
      element.memo = `${element.key} ${element.memo}`
    }
    return list
  }

  get cascaderList () { // 参数级联数据
    const list = [
      {
        key: 'fixed',
        memo: '系统参数',
        children: this.publicList
      },
      {
        key: 'custom',
        memo: '自定义参数',
        children: this.customParametersList
      }
    ]
    return list
  }

  private publicList: any = []
  private getPublicCustom () {
    const url = '/base/action/general/cache/query'
    commonAction({ url, method: 'post', data: { types: ['ivrSystemVariableList'] } }).then(res => {
      if (res.success) {
        this.publicList = res.ivrSystemVariableList || []
      }
    })
  }

  private checkPublic (val) {
    const list = this.publicList.map(i => i.key)
    if (list.includes(val)) {
      (this as any).$message.warning(`系统变量中含有${val}, 请输入其他变量名`)
    }
  }

  private handleChange (val) {
    console.log(this.formData)
  }

  get checkKey () {
    const keyList = this.formData.variableList.map(i => i.value) || []
    const publicList = this.publicList?.map(i => i.key) || []
    const checkKey = (rule, value, callback) => {
      if (!new RegExp('^[A-Za-z0-9_]{0,50}$').test(value)) {
        callback(new Error('支持大小写英文+数字+下划线格式，区分大小写，至多50字符'))
      } else if (value && keyList.filter(i => i === value).length > 1) {
        callback(new Error('自定义名已存在'))
      } else if (publicList.includes(value)) {
        callback(new Error('与系统参数冲突'))
      } else {
        callback()
      }
    }
    return { trigger: 'blur', validator: checkKey }
  }
}
</script>
<style lang='stylus' scoped>
$config-color = #a5a5ad
.audioProgress
  margin 0 10px 0
.tip-span
  color $icon-gray
  font-size 12px
  cursor pointer
.has-config
  display flex
  align-items center
  .V7_iconfont
    margin-left 10px
    cursor pointer
    color $config-color
.select-group-start
  display flex
  /deep/.el-form-item
    width 50%
    margin-right 10px
.delete-span
  cursor pointer
  &:hover
    color $c-danger
.add-span
  font-size 12px
  cursor pointer
  &:before
    margin-right 4px
.select-oprate
  display flex
  align-items center
.addVariableList
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #008BEE;
  line-height: 44px;
  cursor pointer
.instructions
  height: 14px;
  line-height 14px
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 600;
  color: #303753;
  margin-bottom 12px
  i
    font-size 14px
    color #FAAE14
    margin-right 5px
.details
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #767E91;
  margin-left 7px
  margin-bottom 39px
</style>
